﻿using System;
using Newtonsoft.Json;
using WebCommon.Com;

namespace Payment.Weixin2
{
    /// <summary>
    /// PostJsapi
    /// </summary>
    public class PostJsapi
    {
        /// <summary>
        /// 微信配置
        /// </summary>
        private WxConfig wxConfig;

        /// <summary>
        /// 随即字符串
        /// </summary>
        private string nonceStr;

        /// <summary>
        /// 时间戳
        /// </summary>
        private string timeStamp;

        /// <summary>
        /// 业务参数
        /// </summary>
        public string package;

        /// <summary>
        /// 密钥
        /// </summary>
        public string paySign;

        private IPayOrder payOrder;
        public PostJsapi(IPayOrder payOrder, WxConfig wxConfig)
        {
            this.wxConfig = wxConfig;
            this.payOrder = payOrder;
        }

        /// <summary>
        /// 
        /// </summary>
        public PostJsapi(IPayOrder payOrder, WxConfig wxConfig, string openid, string ip)
            : this(payOrder, wxConfig)
        {
            this.nonceStr = new RandomsAzNum(16).OutputAzLower();
            this.timeStamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
            wxPackage = new WxPackage(this.payOrder, wxConfig, ip, nonceStr);
            wxSign = new WxSign(wxPackage);
            this.paySign = wxSign.GetSign(this.wxConfig.Key);
            this.package = wxPackage.PostUrl(this.paySign, openid);

        }

        public WxPackage wxPackage { get; private set; }
        public WxSign wxSign { get; private set; }

        /// <summary>
        /// 获取jaapi参数模型
        /// </summary>
        /// <returns></returns>
        public JsapiObj GetJsapiJson()
        {
            var jo = new JsapiObj();
            jo.appId = this.wxConfig.AppId;
            jo.nonceStr = this.nonceStr;
            jo.timeStamp = this.timeStamp;
            jo.package = "prepay_id=" + this.package;
            jo.paySign = this.paySign;
            return jo;
        }
    }
}